<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="套餐编号" prop="packageId">
        <el-input v-model="formData.packageId" placeholder="请输入套餐编号" />
      </el-form-item>
      <el-form-item label="维度名称" prop="categoryName">
        <!-- <el-input v-model="formData.categoryName" placeholder="请输入维度名称" /> -->
        <el-select
          v-model="formData.categoryName"
          placeholder="请选择维度名称"
          @change="handlecategoryNameChange"
        >
          <el-option
            v-for="item in categorys"
            :key="item.id"
            :label="item.description"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配置" prop="ids">
        <!-- <el-input v-model="formData.ids" placeholder="请输入配置" /> -->
        <el-card class="w-full h-400px !overflow-y-scroll" shadow="never">
          <template #header>
            全选/全不选:
            <el-switch
              v-model="treeNodeAll"
              active-text="是"
              inactive-text="否"
              inline-prompt
              @change="handleCheckedTreeNodeAll"
            />
            全部展开/折叠:
            <el-switch
              v-model="menuExpand"
              active-text="展开"
              inactive-text="折叠"
              inline-prompt
              @change="handleCheckedTreeExpand"
            />
          </template>
          <el-tree
            ref="treeRef"
            :data="items"
            :props="defaultProps"
            empty-text="加载中，请稍候"
            node-key="id"
            show-checkbox
          />
        </el-card>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { PackageSettingApi, PackageSetting } from '@/api/system/packagesetting'
import { PackageCategoryApi } from '@/api/system/packagecategory'
import { handleTree } from '@/utils/tree'
import { ElTree } from 'element-plus'

/** 示例联系人 表单 */
defineOptions({ name: 'PackageSettingForm' })
const defaultProps = ref({
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
})
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const treeRef = ref<InstanceType<typeof ElTree>>() // 树组件 Ref
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  packageId: undefined as number | undefined,
  categoryName: undefined as number | undefined,
  ids: []
})
const formRules = reactive({
  packageId: [{ required: true, message: '套餐编号不能为空', trigger: 'blur' }],
  categoryName: [{ required: true, message: '维度名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, packageId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (packageId) {
    formData.value.packageId = packageId
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await PackageSettingApi.getPackageSetting(id)
      if (data) {
        formData.value = data
        await handlecategoryNameChange(data.categoryName)
      } else {
        message.warning(t('common.getFailed'))
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PackageSetting
    data.ids = [
      ...(treeRef.value!.getCheckedKeys(false) as unknown as Array<number>), // 获得当前选中节点
      ...(treeRef.value!.getHalfCheckedKeys() as unknown as Array<number>) // 获得半选中的父节点
    ]
    if (formType.value === 'create') {
      await PackageSettingApi.createPackageSetting(data)
      message.success(t('common.createSuccess'))
    } else {
      await PackageSettingApi.updatePackageSetting(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const treeNodeAll = ref(false) // 全选/全不选
const menuExpand = ref(false) // 展开/折叠
/** 全选/全不选 */
const handleCheckedTreeNodeAll = () => {
  treeRef.value!.setCheckedNodes(treeNodeAll.value ? items.value : [])
} /** 展开/折叠全部 */
const handleCheckedTreeExpand = () => {
  const nodes = treeRef.value?.store.nodesMap
  for (let node in nodes) {
    if (nodes[node].expanded === menuExpand.value) {
      continue
    }
    nodes[node].expanded = menuExpand.value
  }
}

const items = ref<any[]>([])
const handlecategoryNameChange = async (name: string) => {
  const cate = categorys.value.find((item) => {item.name === name})
  if (cate && cate.showField) {
    defaultProps.value.label = cate.showField
  }
  const data = await PackageCategoryApi.getCategoryItems(name)
  items.value = handleTree(data)
  await nextTick()

  if (formData.value.ids.length > 0) {
    formData.value.ids.forEach((id: number) => {
      console.log('formData.value.ids', id)
      treeRef.value!.setChecked(id, true, false)
    })
  }
}

/** 重置表单 */
const resetForm = () => {
  // 重置选项
  treeNodeAll.value = false
  menuExpand.value = false
  formData.value = {
    packageId: undefined as number | undefined,
    categoryName: undefined as number | undefined,
    ids: []
  }
  formRef.value?.resetFields()
}
const categorys = ref([])

onMounted(async () => {
  // 获取字典
  categorys.value = await PackageCategoryApi.getPackageCategoryList({})
})
</script>
